<template>
  <div class="scroll-load">
    <ul class="list">
      <li v-for="d in list" :key="d">{{ d }}</li>
    </ul>
    <div class="loading">
      正在加载...
    </div>
  </div>
</template>

<script>
const ajax = ()=>{
  return new Promise(resolve=>{
    setTimeout(()=>{
      resolve(new Array(5).fill(0).map(()=>Math.random()));
    },Math.random()* 1000)
  })
}
  export default {
    data(){
      return {
        list:[],
        loading:false
      }
    },
    methods:{
      onScroll(){
        console.log('发生滚动');
        if(!this.loading() && this.needLoad()){
          this.getList()
        }
      },
      getList(){
        this.loading=true,
        ajax().then(data => {
          // this.list = this.list.concat(data)
          //展开运算符 可以合并对象或数组
          this.list = [...this.list,...data]
        });
        this.loading=false
        //判断数据是否占满可视区,其实就是判断needLoad是不是false,setTimeout是为了保证前面给list增加数据导致的视图更新已经完成了
        setTimeout(()=>{
          if(this.needLoad()){
            this.getList()
          }
        },0)
      },
      //判断是否需要加载,底部的那个正在加载的DOM和可视区顶部的距离小于可视区高度
      needLoad(){
        const clientHeight = document.documentElement.clientHeight
        //getBoundingClientRect()任意元素距离可视区的位置
        const { top } = document.querySelector('.loading').getBoundingClientRect()
        return top <= (clientHeight + 500)
      }
    },
    //创建
    mounted(){
      this.getList()
      window.addEventListener('scroll',this.onScroll)
    },
    //相当于小程序的onUnload
    beforeDestroy(){
      window.removeEventListener('scroll',this.onScroll)
    }
  }
</script>

<style lang="sass" scoped>
.scroll-load
  text-align: center
  .list
    width: 500px
    margin: 0 auto
    li
      line-height: 50px
      &:nth-child(odd)
        background: #f0c0f0
      &:nth-child(even)
        background: #f55

</style>
